-- Lua Battle System - 数据驱动的优化反馈循环系统
-- 整合AI参数调优、性能监控和配置管理，形成完整的优化闭环

local Logger = require("utils.logger")
local TableUtils = require("utils.table_utils")
local DynamicConfigManager = require("config.dynamic_config_manager")
local PerformanceMonitor = require("utils.performance_monitor")
local AIParameterTuner = require("ai.ai_parameter_tuner")

local OptimizationFeedbackLoop = {
    -- 反馈循环配置
    config = {
        -- 循环控制
        loop_interval = 60, -- 循环检查间隔（秒）
        optimization_cycles_per_hour = 6, -- 每小时优化周期数

        -- 数据收集
        data_collection = {
            enabled = true,
            sample_size = 100, -- 数据样本大小
            collection_window = 300, -- 数据收集窗口（秒）
            min_data_points = 10 -- 最小数据点数
        },

        -- 优化触发条件
        optimization_triggers = {
            performance_degradation = 0.15, -- 性能下降阈值（15%）
            ai_quality_decline = 0.1, -- AI质量下降阈值（10%）
            resource_usage_high = 0.8, -- 资源使用率高阈值（80%）
            error_rate_increase = 0.05, -- 错误率增加阈值（5%）
            user_feedback_negative = 0.3 -- 用户负面反馈阈值（30%）
        },

        -- 优化策略权重
        optimization_weights = {
            performance_tuning = 0.4, -- 性能调优权重
            ai_parameter_optimization = 0.3, -- AI参数优化权重
            configuration_adjustment = 0.2, -- 配置调整权重
            resource_management = 0.1 -- 资源管理权重
        },

        -- 反馈控制
        feedback_control = {
            enable_adaptive_tuning = true, -- 启用自适应调优
            conservative_mode = false, -- 保守模式
            maximum_daily_optimizations = 24, -- 每日最大优化次数
            optimization_cooldown = 300, -- 优化冷却时间（秒）
            rollback_on_failure = true -- 失败时回滚
        }
    },

    -- 当前状态
    state = {
        is_active = false,
        start_time = 0,
        last_optimization_time = 0,
        optimization_count = 0,
        daily_optimization_count = 0,
        last_day_reset = 0,

        -- 性能基线
        performance_baseline = {
            overall_score = 0.8,
            ai_decision_quality = 0.75,
            response_time = 50,
            resource_usage = 0.6
        },

        -- 当前性能
        current_performance = {},

        -- 优化历史
        optimization_history = [],

        -- 反馈数据
        feedback_data = {
            performance_metrics = {},
            ai_metrics = {},
            user_feedback = {},
            system_events = {}
        },

        -- 优化结果统计
        optimization_stats = {
            successful_optimizations = 0,
            failed_optimizations = 0,
            rollbacks = 0,
            performance_improvements = {},
            performance_degradations = {}
        }
    },

    -- 子系统引用
    subsystems = {
        config_manager = nil,
        performance_monitor = nil,
        ai_parameter_tuner = nil
    }
}

-- 初始化优化反馈循环
function OptimizationFeedbackLoop:init(config)
    Logger.info("初始化优化反馈循环系统")

    -- 合并配置
    if config then
        TableUtils.merge(self.config, config)
    end

    -- 初始化子系统
    self:init_subsystems()

    -- 初始化性能基线
    self:init_performance_baseline()

    self.state.start_time = os.time()
    self.state.last_day_reset = os.time()

    Logger.info("优化反馈循环系统初始化完成", {
        loop_interval = self.config.loop_interval,
        subsystems_initialized = self:get_initialized_subsystem_count()
    })
end

-- 初始化子系统
function OptimizationFeedbackLoop:init_subsystems()
    Logger.info("初始化子系统")

    -- 初始化配置管理器
    self.subsystems.config_manager = DynamicConfigManager:new({
        file_monitoring = {enabled = true, auto_reload = true},
        validation = {strict_mode = true, validate_on_change = true},
        history = {enabled = true, max_history_size = 100}
    })

    -- 初始化性能监控器
    self.subsystems.performance_monitor = PerformanceMonitor:new({
        monitoring_interval = 5,
        auto_tuning = {enabled = true, aggressive_mode = false},
        alerting = {enabled = true, alert_cooldown = 60}
    })

    -- 初始化AI参数调优器
    self.subsystems.ai_parameter_tuner = AIParameterTuner:new({
        learning_rate = 0.1,
        tuning_interval = 10,
        tuning_threshold = 0.15,
        strategy = "gradient_descent"
    })

    -- 建立子系统之间的连接
    self:establish_subsystem_connections()

    Logger.info("子系统初始化完成")
end

-- 建立子系统连接
function OptimizationFeedbackLoop:establish_subsystem_connections()
    -- 性能监控器连接AI参数调优器
    self.subsystems.performance_monitor:set_ai_parameter_tuner(self.subsystems.ai_parameter_tuner)

    -- 设置性能监控告警回调
    self.subsystems.performance_monitor:set_alert_callback(function(alert)
        self:handle_performance_alert(alert)
    end)

    -- 设置配置变更监听器
    for config_name, _ in pairs(self.subsystems.config_manager:get_registered_config_names()) do
        self.subsystems.config_manager:add_change_listener(
            config_name,
            "optimization_feedback_loop",
            function(name, data, change_info)
                self:handle_config_change(name, data, change_info)
            end
        )
    end

    Logger.info("子系统连接建立完成")
end

-- 获取已初始化的子系统数量
function OptimizationFeedbackLoop:get_initialized_subsystem_count()
    local count = 0
    for _, subsystem in pairs(self.subsystems) do
        if subsystem then
            count = count + 1
        end
    end
    return count
end

-- 初始化性能基线
function OptimizationFeedbackLoop:init_performance_baseline()
    Logger.info("初始化性能基线")

    -- 收集初始性能数据
    local initial_performance = self:collect_current_performance()

    if initial_performance then
        self.state.performance_baseline = {
            overall_score = initial_performance.overall_score or 0.8,
            ai_decision_quality = initial_performance.ai_decision_quality or 0.75,
            response_time = initial_performance.response_time or 50,
            resource_usage = initial_performance.resource_usage or 0.6,
            timestamp = os.time()
        }

        Logger.info("性能基线建立完成", self.state.performance_baseline)
    else
        Logger.warn("无法建立性能基线，使用默认值")
    end
end

-- 启动优化反馈循环
function OptimizationFeedbackLoop:start()
    if self.state.is_active then
        Logger.warn("优化反馈循环已在运行")
        return false
    end

    self.state.is_active = true
    self.state.start_time = os.time()

    Logger.info("优化反馈循环已启动")

    -- 启动子系统
    self.subsystems.performance_monitor:start_monitoring()

    -- 启动主循环
    self:main_loop()

    return true
end

-- 停止优化反馈循环
function OptimizationFeedbackLoop:stop()
    if not self.state.is_active then
        Logger.warn("优化反馈循环未在运行")
        return false
    end

    self.state.is_active = false

    Logger.info("优化反馈循环已停止")
    return true
end

-- 主循环
function OptimizationFeedbackLoop:main_loop()
    if not self.state.is_active then
        return
    end

    local current_time = os.time()

    -- 检查是否到了优化时间
    if current_time - self.state.last_optimization_time >= self.config.loop_interval then
        self:execute_optimization_cycle()
        self.state.last_optimization_time = current_time
    end

    -- 每日重置
    self:check_daily_reset(current_time)

    -- 数据收集
    if self.config.data_collection.enabled then
        self:collect_feedback_data()
    end
end

-- 检查每日重置
function OptimizationFeedbackLoop:check_daily_reset(current_time)
    -- 检查是否是新的一天
    local current_day = os.date("*t", current_time)
    local last_day = os.date("*t", self.state.last_day_reset)

    if current_day.day ~= last_day.day or current_day.month ~= last_day.month or current_day.year ~= last_day.year then
        self:reset_daily_counters()
        self.state.last_day_reset = current_time
    end
end

-- 重置每日计数器
function OptimizationFeedbackLoop:reset_daily_counters()
    Logger.info("重置每日优化计数器")
    self.state.daily_optimization_count = 0

    -- 清理过期数据
    self:cleanup_expired_data()
end

-- 执行优化周期
function OptimizationFeedbackLoop:execute_optimization_cycle()
    Logger.debug("执行优化周期")

    -- 检查优化限制
    if not self:can_execute_optimization() then
        return
    end

    -- 收集当前性能数据
    local current_performance = self:collect_current_performance()
    if not current_performance then
        Logger.warn("无法收集性能数据，跳过优化周期")
        return
    end

    self.state.current_performance = current_performance

    -- 评估优化需求
    local optimization_needs = self:evaluate_optimization_needs(current_performance)

    if optimization_needs.requires_optimization then
        Logger.info("检测到优化需求", optimization_needs)

        -- 执行优化
        local optimization_result = self:execute_optimization(optimization_needs)

        -- 记录优化历史
        self:record_optimization_history(optimization_needs, optimization_result)

        -- 更新统计
        self:update_optimization_stats(optimization_result)
    else
        Logger.debug("当前性能良好，无需优化")
    end
end

-- 检查是否可以执行优化
function OptimizationFeedbackLoop:can_execute_optimization()
    -- 检查每日优化次数限制
    if self.state.daily_optimization_count >= self.config.optimization_control.maximum_daily_optimizations then
        Logger.debug("已达到每日最大优化次数")
        return false
    end

    -- 检查优化冷却时间
    local time_since_last_optimization = os.time() - self.state.last_optimization_time
    if time_since_last_optimization < self.config.optimization_control.optimization_cooldown then
        Logger.debug("优化冷却时间未到")
        return false
    end

    -- 检查是否有足够的数据
    if not self:has_sufficient_data() then
        Logger.debug("数据不足，无法执行优化")
        return false
    end

    return true
end

-- 检查是否有足够的数据
function OptimizationFeedbackLoop:has_sufficient_data()
    local performance_metrics = self.state.feedback_data.performance_metrics
    return #performance_metrics >= self.config.data_collection.min_data_points
end

-- 收集当前性能数据
function OptimizationFeedbackLoop:collect_current_performance()
    local performance_data = {}

    -- 从性能监控器获取数据
    local monitor_data = self.subsystems.performance_monitor:get_performance_data()
    if monitor_data and monitor_data.current then
        local perf = monitor_data.current

        performance_data.overall_score = self.subsystems.performance_monitor.state.health_score
        performance_data.response_time = perf.response_time.current
        performance_data.memory_usage = perf.memory_usage.current
        performance_data.cpu_usage = perf.cpu_usage.current
        performance_data.error_rate = perf.error_rate.current
    end

    -- 从AI参数调优器获取数据
    if self.subsystems.ai_parameter_tuner then
        local ai_report = self.subsystems.ai_parameter_tuner:get_tuning_report()
        if ai_report then
            performance_data.ai_decision_quality = 0.8 -- 基于AI报告计算质量分数
            performance_data.ai_tuning_frequency = ai_report.summary.tuning_cycles or 0
        end
    end

    -- 计算综合资源使用率
    performance_data.resource_usage = (
        (performance_data.memory_usage or 0) + (performance_data.cpu_usage or 0)
    ) / 2

    return performance_data
end

-- 评估优化需求
function OptimizationFeedbackLoop:evaluate_optimization_needs(current_performance)
    local needs = {
        requires_optimization = false,
        primary_issues = {},
        recommended_strategies = {},
        urgency_level = "low"
    }

    local baseline = self.state.performance_baseline
    local triggers = self.config.optimization_triggers

    -- 检查性能下降
    local performance_drop = baseline.overall_score - (current_performance.overall_score or 0)
    if performance_drop > triggers.performance_degradation then
        needs.requires_optimization = true
        table.insert(needs.primary_issues, {
            type = "performance_degradation",
            severity = performance_drop,
            description = string.format("性能下降 %.1f%%", performance_drop * 100)
        })
        table.insert(needs.recommended_strategies, "performance_tuning")
    end

    -- 检查AI质量下降
    local ai_quality_drop = baseline.ai_decision_quality - (current_performance.ai_decision_quality or 0)
    if ai_quality_drop > triggers.ai_quality_decline then
        needs.requires_optimization = true
        table.insert(needs.primary_issues, {
            type = "ai_quality_decline",
            severity = ai_quality_drop,
            description = string.format("AI决策质量下降 %.1f%%", ai_quality_drop * 100)
        })
        table.insert(needs.recommended_strategies, "ai_parameter_optimization")
    end

    -- 检查资源使用率
    local resource_usage = current_performance.resource_usage or 0
    if resource_usage > triggers.resource_usage_high then
        needs.requires_optimization = true
        table.insert(needs.primary_issues, {
            type = "high_resource_usage",
            severity = resource_usage,
            description = string.format("资源使用率过高: %.1f%%", resource_usage * 100)
        })
        table.insert(needs.recommended_strategies, "resource_management")
    end

    -- 检查错误率增加
    local error_rate = current_performance.error_rate or 0
    if error_rate > triggers.error_rate_increase then
        needs.requires_optimization = true
        table.insert(needs.primary_issues, {
            type = "high_error_rate",
            severity = error_rate,
            description = string.format("错误率过高: %.2f%%", error_rate * 100)
        })
        table.insert(needs.recommended_strategies, "configuration_adjustment")
    end

    -- 确定紧急程度
    local max_severity = 0
    for _, issue in ipairs(needs.primary_issues) do
        max_severity = math.max(max_severity, issue.severity)
    end

    if max_severity > 0.3 then
        needs.urgency_level = "critical"
    elseif max_severity > 0.15 then
        needs.urgency_level = "high"
    elseif max_severity > 0.05 then
        needs.urgency_level = "medium"
    end

    return needs
end

-- 执行优化
function OptimizationFeedbackLoop:execute_optimization(optimization_needs)
    Logger.info("开始执行优化", {
        strategies = table.concat(optimization_needs.recommended_strategies, ", "),
        urgency = optimization_needs.urgency_level
    })

    local results = {
        success = false,
        applied_strategies = {},
        performance_change = {},
        errors = {}
    }

    self.state.daily_optimization_count = self.state.daily_optimization_count + 1
    self.state.optimization_count = self.state.optimization_count + 1

    local strategies_by_priority = self:prioritize_optimization_strategies(optimization_needs.recommended_strategies)

    -- 执行优化策略
    for _, strategy_info in ipairs(strategies_by_priority) do
        local strategy_result = self:execute_optimization_strategy(strategy_info.strategy, optimization_needs)

        table.insert(results.applied_strategies, {
            strategy = strategy_info.strategy,
            priority = strategy_info.priority,
            result = strategy_result
        })

        if strategy_result.success then
            results.success = true
        else
            table.insert(results.errors, {
                strategy = strategy_info.strategy,
                error = strategy_result.error
            })
        end

        -- 在保守模式下，成功一个策略就停止
        if self.config.optimization_control.conservative_mode and results.success then
            break
        end
    end

    -- 计算性能变化
    results.performance_change = self:calculate_performance_change()

    Logger.info("优化执行完成", {
        success = results.success,
        strategies_applied = #results.applied_strategies,
        daily_count = self.state.daily_optimization_count
    })

    return results
end

-- 优先级排序优化策略
function OptimizationFeedbackLoop:prioritize_optimization_strategies(strategies)
    local weights = self.config.optimization_weights
    local prioritized = {}

    for _, strategy in ipairs(strategies) do
        local weight = weights[strategy] or 0.1
        table.insert(prioritized, {
            strategy = strategy,
            priority = weight,
            weight = weight
        })
    end

    -- 按权重排序
    table.sort(prioritized, function(a, b)
        return a.weight > b.weight
    end)

    return prioritized
end

-- 执行单个优化策略
function OptimizationFeedbackLoop:execute_optimization_strategy(strategy, optimization_needs)
    local result = {
        success = false,
        strategy = strategy,
        timestamp = os.time(),
        details = {}
    }

    Logger.debug("执行优化策略", {strategy = strategy})

    if strategy == "performance_tuning" then
        result = self:execute_performance_tuning(optimization_needs)
    elseif strategy == "ai_parameter_optimization" then
        result = self:execute_ai_parameter_optimization(optimization_needs)
    elseif strategy == "configuration_adjustment" then
        result = self:execute_configuration_adjustment(optimization_needs)
    elseif strategy == "resource_management" then
        result = self:execute_resource_management(optimization_needs)
    else
        result.error = "未知的优化策略: " .. strategy
        Logger.warn(result.error)
    end

    return result
end

-- 执行性能调优
function OptimizationFeedbackLoop:execute_performance_tuning(optimization_needs)
    local result = {
        success = false,
        strategy = "performance_tuning",
        timestamp = os.time()
    }

    -- 触发性能监控器的自动调优
    local perf_report = self.subsystems.performance_monitor:trigger_analysis()

    if perf_report and perf_report.health_score and perf_report.health_score > 0.5 then
        result.success = true
        result.details = {
            health_score = perf_report.health_score,
            recommendations = perf_report.recommendations
        }

        -- 应用性能优化建议
        self:apply_performance_recommendations(perf_report.recommendations)
    else
        result.error = "性能调优未达到预期效果"
    end

    return result
end

-- 执行AI参数优化
function OptimizationFeedbackLoop:execute_ai_parameter_optimization(optimization_needs)
    local result = {
        success = false,
        strategy = "ai_parameter_optimization",
        timestamp = os.time()
    }

    -- 触发AI参数调优
    local tuning_success = self.subsystems.ai_parameter_tuner:force_tuning()

    if tuning_success then
        result.success = true
        result.details = {
            tuning_cycles = self.subsystems.ai_parameter_tuner.state.tuning_cycle
        }
    else
        result.error = "AI参数调优失败"
    end

    return result
end

-- 执行配置调整
function OptimizationFeedbackLoop:execute_configuration_adjustment(optimization_needs)
    local result = {
        success = false,
        strategy = "configuration_adjustment",
        timestamp = os.time()
    }

    local adjustments = self:calculate_config_adjustments(optimization_needs)
    local applied_adjustments = 0

    for config_name, config_changes in pairs(adjustments) do
        local success = self.subsystems.config_manager:batch_update_config(config_name, config_changes)
        if success then
            applied_adjustments = applied_adjustments + 1
        end
    end

    if applied_adjustments > 0 then
        result.success = true
        result.details = {
            adjustments_made = applied_adjustments,
            changes = adjustments
        }
    else
        result.error = "配置调整失败"
    end

    return result
end

-- 执行资源管理优化
function OptimizationFeedbackLoop:execute_resource_management(optimization_needs)
    local result = {
        success = false,
        strategy = "resource_management",
        timestamp = os.time()
    }

    -- 强制垃圾回收
    local memory_before = collectgarbage("count")
    collectgarbage("collect")
    local memory_after = collectgarbage("count")

    local memory_freed = memory_before - memory_after

    if memory_freed > 100 then -- 释放超过100KB认为有效
        result.success = true
        result.details = {
            memory_freed_kb = memory_freed,
            memory_before_kb = memory_before,
            memory_after_kb = memory_after
        }
    else
        result.error = "资源管理优化效果不明显"
    end

    return result
end

-- 计算配置调整
function OptimizationFeedbackLoop:calculate_config_adjustments(optimization_needs)
    local adjustments = {}

    -- 基于性能问题动态调整配置
    for _, issue in ipairs(optimization_needs.primary_issues) do
        if issue.type == "high_resource_usage" then
            -- 降低性能相关配置
            adjustments.battle = adjustments.battle or {}
            adjustments.battle.ai = adjustments.battle.ai or {}
            adjustments.battle.ai.decision_time_limit = 0.5 -- 减少AI决策时间
        elseif issue.type == "performance_degradation" then
            -- 优化性能配置
            adjustments.performance = adjustments.performance or {}
            adjustments.performance.monitoring = adjustments.performance.monitoring or {}
            adjustments.performance.monitoring.interval = 10 -- 增加监控间隔
        end
    end

    return adjustments
end

-- 应用性能优化建议
function OptimizationFeedbackLoop:apply_performance_recommendations(recommendations)
    if not recommendations then
        return
    end

    for _, recommendation in ipairs(recommendations) do
        if recommendation.action and recommendation.target then
            -- 根据建议类型执行相应操作
            if recommendation.action == "increase_tuning_frequency" then
                self.config.loop_interval = math.max(30, self.config.loop_interval - 10)
            end
        end
    end
end

-- 计算性能变化
function OptimizationFeedbackLoop:calculate_performance_change()
    local current = self.state.current_performance
    local baseline = self.state.performance_baseline

    if not current or not baseline then
        return {}
    end

    local change = {}
    if current.overall_score and baseline.overall_score then
        change.overall_score = current.overall_score - baseline.overall_score
    end
    if current.response_time and baseline.response_time then
        change.response_time = current.response_time - baseline.response_time
    end
    if current.resource_usage and baseline.resource_usage then
        change.resource_usage = current.resource_usage - baseline.resource_usage
    end

    return change
end

-- 收集反馈数据
function OptimizationFeedbackLoop:collect_feedback_data()
    local current_time = os.time()

    -- 收集性能指标
    local performance_metrics = self:collect_current_performance()
    if performance_metrics then
        performance_metrics.timestamp = current_time
        table.insert(self.state.feedback_data.performance_metrics, performance_metrics)

        -- 限制数据量
        while #self.state.feedback_data.performance_metrics > self.config.data_collection.sample_size do
            table.remove(self.state.feedback_data.performance_metrics, 1)
        end
    end

    -- 收集AI指标
    if self.subsystems.ai_parameter_tuner then
        local ai_report = self.subsystems.ai_parameter_tuner:get_tuning_report()
        if ai_report then
            local ai_metrics = {
                timestamp = current_time,
                tuning_cycles = ai_report.summary.tuning_cycles,
                optimization_progress = ai_report.summary.optimization_progress,
                current_strategy = ai_report.summary.current_strategy
            }
            table.insert(self.state.feedback_data.ai_metrics, ai_metrics)

            while #self.state.feedback_data.ai_metrics > self.config.data_collection.sample_size do
                table.remove(self.state.feedback_data.ai_metrics, 1)
            end
        end
    end
end

-- 处理性能告警
function OptimizationFeedbackLoop:handle_performance_alert(alert)
    Logger.info("收到性能告警", alert)

    -- 根据告警严重程度决定是否立即优化
    if alert.severity == "critical" then
        Logger.info("严重告警，立即触发优化")
        self:execute_emergency_optimization(alert)
    end

    -- 记录系统事件
    table.insert(self.state.feedback_data.system_events, {
        type = "performance_alert",
        timestamp = os.time(),
        alert = alert
    })
end

-- 执行紧急优化
function OptimizationFeedbackLoop:execute_emergency_optimization(alert)
    local emergency_needs = {
        requires_optimization = true,
        primary_issues = {{
            type = "emergency_alert",
            severity = 1.0,
            description = "紧急性能告警: " .. alert.message
        }},
        recommended_strategies = {"performance_tuning", "resource_management"},
        urgency_level = "critical"
    }

    self:execute_optimization(emergency_needs)
end

-- 处理配置变更
function OptimizationFeedbackLoop:handle_config_change(config_name, config_data, change_info)
    Logger.debug("配置变更", {
        config = config_name,
        change_type = change_info and change_info.type or "unknown"
    })

    -- 记录系统事件
    table.insert(self.state.feedback_data.system_events, {
        type = "config_change",
        timestamp = os.time(),
        config_name = config_name,
        change_info = change_info
    })
end

-- 记录优化历史
function OptimizationFeedbackLoop:record_optimization_history(needs, result)
    local history_entry = {
        timestamp = os.time(),
        optimization_count = self.state.optimization_count,
        needs = needs,
        result = result,
        performance_before = TableUtils.deep_copy(self.state.performance_baseline),
        performance_after = TableUtils.deep_copy(self.state.current_performance)
    }

    table.insert(self.state.optimization_history, history_entry)

    -- 限制历史记录数量
    while #self.state.optimization_history > 100 do
        table.remove(self.state.optimization_history, 1)
    end
end

-- 更新优化统计
function OptimizationFeedbackLoop:update_optimization_stats(result)
    if result.success then
        self.state.optimization_stats.successful_optimizations =
            self.state.optimization_stats.successful_optimizations + 1

        -- 记录性能改进
        if result.performance_change and result.performance_change.overall_score > 0 then
            table.insert(self.state.optimization_stats.performance_improvements, {
                timestamp = os.time(),
                improvement = result.performance_change.overall_score
            })
        end
    else
        self.state.optimization_stats.failed_optimizations =
            self.state.optimization_stats.failed_optimizations + 1
    end

    -- 检查是否需要回滚
    if self.config.optimization_control.rollback_on_failure and not result.success then
        self:execute_rollback(result)
    end
end

-- 执行回滚
function OptimizationFeedbackLoop:execute_rollback(failed_optimization)
    Logger.warn("执行优化回滚", failed_optimization)

    -- 这里可以实现具体的回滚逻辑
    -- 例如恢复配置参数、AI参数等

    self.state.optimization_stats.rollbacks = self.state.optimization_stats.rollbacks + 1
end

-- 清理过期数据
function OptimizationFeedbackLoop:cleanup_expired_data()
    local cutoff_time = os.time() - self.config.data_collection.collection_window

    -- 清理性能指标数据
    local filtered_metrics = {}
    for _, metric in ipairs(self.state.feedback_data.performance_metrics) do
        if metric.timestamp >= cutoff_time then
            table.insert(filtered_metrics, metric)
        end
    end
    self.state.feedback_data.performance_metrics = filtered_metrics

    -- 清理AI指标数据
    local filtered_ai_metrics = {}
    for _, metric in ipairs(self.state.feedback_data.ai_metrics) do
        if metric.timestamp >= cutoff_time then
            table.insert(filtered_ai_metrics, metric)
        end
    end
    self.state.feedback_data.ai_metrics = filtered_ai_metrics
end

-- 获取优化报告
function OptimizationFeedbackLoop:get_optimization_report()
    local current_performance = self:collect_current_performance() or {}

    return {
        system_status = {
            is_active = self.state.is_active,
            uptime = os.time() - self.state.start_time,
            optimization_count = self.state.optimization_count,
            daily_optimization_count = self.state.daily_optimization_count
        },

        current_performance = current_performance,
        performance_baseline = self.state.performance_baseline,

        optimization_statistics = self.state.optimization_stats,
        recent_optimizations = self:get_recent_optimizations(5),

        feedback_data_summary = {
            performance_metrics_count = #self.state.feedback_data.performance_metrics,
            ai_metrics_count = #self.state.feedback_data.ai_metrics,
            user_feedback_count = #self.state.feedback_data.user_feedback,
            system_events_count = #self.state.feedback_data.system_events
        },

        subsystems_status = {
            config_manager = self.subsystems.config_manager:health_check(),
            performance_monitor = self.subsystems.performance_monitor:get_performance_data(),
            ai_parameter_tuner = self.subsystems.ai_parameter_tuner:get_tuning_report()
        }
    }
end

-- 获取最近的优化记录
function OptimizationFeedbackLoop:get_recent_optimizations(count)
    local recent = {}
    local start_idx = math.max(1, #self.state.optimization_history - count + 1)

    for i = start_idx, #self.state.optimization_history do
        table.insert(recent, self.state.optimization_history[i])
    end

    return recent
end

-- 手动触发优化
function OptimizationFeedbackLoop:trigger_manual_optimization(strategy)
    Logger.info("手动触发优化", {strategy = strategy})

    local manual_needs = {
        requires_optimization = true,
        primary_issues = {{
            type = "manual_trigger",
            severity = 0.5,
            description = "手动触发的优化"
        }},
        recommended_strategies = strategy and {strategy} or {"performance_tuning"},
        urgency_level = "medium"
    }

    return self:execute_optimization(manual_needs)
end

-- 设置自适应调优
function OptimizationFeedbackLoop:set_adaptive_tuning(enabled)
    self.config.optimization_control.enable_adaptive_tuning = enabled
    Logger.info("自适应调优" .. (enabled and "已启用" or "已禁用"))
end

-- 设置保守模式
function OptimizationFeedbackLoop:set_conservative_mode(enabled)
    self.config.optimization_control.conservative_mode = enabled
    Logger.info("保守模式" .. (enabled and "已启用" or "已禁用"))
end

-- 健康检查
function OptimizationFeedbackLoop:health_check()
    local health = {
        status = "healthy",
        issues = {},
        subsystems = {}
    }

    -- 检查子系统健康
    local config_health = self.subsystems.config_manager:health_check()
    health.subsystems.config_manager = config_health

    if config_health.status ~= "healthy" then
        table.insert(health.issues, "配置管理器状态异常: " .. config_health.status)
        health.status = "warning"
    end

    -- 检查性能监控器
    local perf_data = self.subsystems.performance_monitor:get_performance_data()
    if perf_data and perf_data.health_score and perf_data.health_score < 0.5 then
        table.insert(health.issues, "性能监控器健康分数过低: " .. perf_data.health_score)
        health.status = "warning"
    end

    -- 检查数据收集状态
    if not self:has_sufficient_data() then
        table.insert(health.issues, "数据收集不足")
        health.status = "warning"
    end

    return health
end

-- 创建优化反馈循环实例
function OptimizationFeedbackLoop:new(config)
    local instance = {
        config = TableUtils.deep_copy(self.config),
        state = TableUtils.deep_copy(self.state),
        subsystems = {}
    }

    setmetatable(instance, {__index = self})

    if config then
        TableUtils.merge(instance.config, config)
    end

    instance:init()

    return instance
end

return OptimizationFeedbackLoop